import request from '@/utils/request'

// 引入相关的依赖
import BpmnModeler from 'bpmn-js/lib/Modeler'
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
import customTranslate from './customTranslate' // 汉化包引入

export default {
  data() {
    return {
      returnId: '',
      bpmnModeler: null,
      canvas: null
    }
  },
  mounted() {
    this.init()
    this.setZoomLevel(1.0) // 设置缩放级别为1.0
    this.autoFit() // 自适应显示流程图
  },

  methods: {
    setZoomLevel(level) {
      const canvas = this.bpmnModeler.get('canvas')
      canvas.zoom(level)
    },
    autoFit() {
      const canvas = this.bpmnModeler.get('canvas')
      canvas.zoom('fit-viewport')
    },
    init() {
      // 将汉化包包装成一个模块
      // eslint-disable-next-line no-unused-vars
      const customTranslateMolude = {
        translate: ['value', customTranslate]
      }
      this.bpmnModeler = new BpmnModeler({
        // 建模
        container: this.$refs.canvas,
        propertiesPanel: {
          // 添加控制板
          parent: '#properties-panel'
        },
        // additionalModules: [
        //   // 右边的属性栏
        //   propertiesProviderModule,
        //   propertiesPanelModule,
        //   customTranslateMolude // 汉化模块
        // ],
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        }
      })
    },
    import(xmlStrWithValues) {
      this.bpmnModeler.importXML(xmlStrWithValues, (err) => {
        console.log(111, err)
        if (!err) {
          this.success()
          this.hidePalette() // 调用隐藏左侧栏的方法
        } else {
          console.log(err)
        }
      })
    },
    hidePalette() {
      const paletteContainer = this.$el.querySelector('.djs-palette')
      paletteContainer.style.display = 'none'
    },
    success() {
      console.log('创建成功!')
      this.bpmnModeler.on('commandStack.changed', () => {
        this.getXML().then((xml) => {
        })
      })
      this.addModelerListener()
      this.addEventBusListener()
    },
    getXML() {
      return new Promise((resolve, reject) => {
        this.bpmnModeler.saveXML({ format: true }, (err, xml) => {
          err ? reject(err) : resolve(xml)
        })
      })
    },
    // 添加绑定事件
    addBpmnListener() {
      const that = this
      // 获取a标签dom节点
      const downloadLink = this.$refs.saveDiagram
      const downloadSvgLink = this.$refs.saveSvg
      // 给图绑定事件，当图有发生改变就会触发这个事件
      this.bpmnModeler.on('commandStack.changed', function() {
        that.saveSVG(function(err, svg) {
          that.setEncoded(downloadSvgLink, 'diagram.svg', err ? null : svg)
        })
        that.saveDiagram(function(err, xml) {
          that.setEncoded(downloadLink, 'diagram.bpmn', err ? null : xml)
        })
      })
    },
    addModelerListener() {
      // 监听 modeler
      const bpmnjs = this.bpmnModeler
      const that = this
      // 'shape.removed', 'connect.end', 'connect.move'
      const events = ['shape.added', 'shape.move.end', 'shape.removed']
      events.forEach(function(event) {
        that.bpmnModeler.on(event, e => {
          var elementRegistry = bpmnjs.get('elementRegistry')
          // eslint-disable-next-line no-unused-vars
          var shape = e.element ? elementRegistry.get(e.element.id) : e.shape
          if (event === 'shape.added') {
            console.log('新增了shape')
          } else if (event === 'shape.move.end') {
            console.log('移动了shape')
          } else if (event === 'shape.removed') {
            console.log('删除了shape')
          }
        })
      })
    },
    addEventBusListener() {
      // 监听 element
      const that = this
      const eventBus = this.bpmnModeler.get('eventBus')
      const eventTypes = ['element.click', 'element.changed']
      eventTypes.forEach(function(eventType) {
        eventBus.on(eventType, function(e) {
          if (!e || e.element.type === 'bpmn:Process') return
          if (eventType === 'element.changed') {
            that.elementChanged(eventType, e)
          } else if (eventType === 'element.click') {
            console.log('点击了element')
          }
        })
      })
    },
    elementChanged(eventType, e) {
      var shape = this.getShape(e.element.id)
      if (!shape) {
        // 若是shape为null则表示删除, 无论是shape还是connect删除都调用此处
        console.log('无效的shape')
        // 由于上面已经用 shape.removed 检测了shape的删除, 因此这里只判断是否是线
        if (this.isSequenceFlow(shape.type)) {
          console.log('删除了线')
        }
      }
      if (!this.isInvalid(shape.type)) {
        if (this.isSequenceFlow(shape.type)) {
          console.log('改变了线')
        }
      }
    },
    getShape(id) {
      var elementRegistry = this.bpmnModeler.get('elementRegistry')
      return elementRegistry.get(id)
    },
    isInvalid(param) { // 判断是否是无效的值
      return param === null || param === undefined || param === ''
    },
    isSequenceFlow(type) { // 判断是否是线
      return type === 'bpmn:SequenceFlow'
    }
  }
}
